package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"regexp"
	"strconv"
	"tie/api/register"
	"tie/initlist/cache"
	"tie/initlist/mysql"
	"tie/inits/model"
	"tie/pkg"
	"time"
)

type Res struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

func SendSms(r *gin.Context) {
	var so register.SendSms
	err := r.ShouldBind(&so)
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "参数错误",
			Data:    nil,
		})
		return
	}

	if !regexp.MustCompile(`^1[3-9]\d{9}$`).MatchString(so.Mobile) {
		r.JSON(400, &Res{
			Code:    400,
			Message: "手机号格式不正确",
			Data:    nil,
		})
		return
	}

	//if so.Mobile >= "1" {
	//	r.JSON(400, &Res{
	//		Code:    400,
	//		Message: "一分钟只能发送一次",
	//		Data:    nil,
	//	})
	//	return
	//}

	code := rand.Intn(9000) + 1000
	codeKey := "sendSms" + so.Mobile
	pkg.SendSms(strconv.Itoa(code), so.Mobile)
	cache.Rdb.Set(cache.Ctx, codeKey, code, time.Minute*5)
	r.JSON(200, &Res{
		Code:    200,
		Message: "验证码发送成功",
		Data:    nil,
	})
	return
}

func Login(r *gin.Context) {
	var so register.User
	err := r.ShouldBind(&so)
	if err != nil {
		r.JSON(400, &Res{
			Code:    400,
			Message: "参数错误",
			Data:    nil,
		})
		return
	}

	tx := mysql.DB.Begin()

	codeKey := "sendSms" + so.Mobile
	result, _ := cache.Rdb.Get(cache.Ctx, codeKey).Result()
	if result != so.SendCode {
		r.JSON(400, &Res{
			Code:    400,
			Message: "验证码错误",
			Data:    nil,
		})
		return
	}

	user := model.User{
		Mobile: so.Mobile,
	}
	if user.Mobile != so.Mobile {
		tx.Rollback()
		r.JSON(400, &Res{
			Code:    400,
			Message: "手机号不存在",
			Data:    nil,
		})
		return
	}

	handler, err := pkg.TokenHandler(strconv.FormatInt(int64(user.ID), 10))
	if err != nil {
		return
	}
	tx.Commit()

	key := fmt.Sprintf("login_list")
	resuct, err := cache.Rdb.Get(cache.Ctx, key).Result()
	if result != "" {
		fmt.Println("使用缓存")
		json.Unmarshal([]byte(resuct), &user)
	} else {
		marshal, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, key, marshal, time.Minute*2)
	}

	r.JSON(200, &Res{
		Code:    200,
		Message: "登录成功",
		Data:    handler,
	})
}
